package cn.tedu.order.tcc;

import cn.tedu.order.entity.Order;
import cn.tedu.order.mapper.OrderMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
@Component
public class OrderTccActionImpl implements OrderTccAction {
    @Resource
    private OrderMapper orderMapper;
    @Transactional
    @Override
    public boolean prepare(BusinessActionContext ctx, Long id, Long userId, Long productId, Integer count, BigDecimal money) {
        orderMapper.createFrozen(
                new Order(id,userId,productId,count,money,0));
        //第一阶段执行成功保存标记
        ResultHolder.setResult(OrderTccAction.class,ctx.getXid(),"p");
        return true; // 第一阶段冻结成功
    }

    @Transactional
    @Override
    public synchronized boolean commit(BusinessActionContext ctx) {
        //第一阶段可能没成功，二阶段不用执行
        //二阶段可能已经执行过一次，不用重复执行
        if (ResultHolder.getResult(OrderTccAction.class, ctx.getXid()) == null){
            return true;
        }
        // 第一阶段向第二阶段传递上下文对象时，先转成 json 进行传递，
        // 会丢失数据的类型信息
        Long orderId = Long.valueOf(
                ctx.getActionContext("orderId").toString());

        orderMapper.updateStatus(orderId, 1); //订单状态改成1，正常状态
        //二阶段执行完后，删除标记
        ResultHolder.removeResult(OrderTccAction.class, ctx.getXid());
        return true; //确认提交成功
    }

    @Transactional
    @Override
    public synchronized boolean rollback(BusinessActionContext ctx) {
        if (ResultHolder.getResult(OrderTccAction.class, ctx.getXid()) == null){
            return true;
        }
        Long orderId = Long.valueOf(
                ctx.getActionContext("orderId").toString());

        orderMapper.deleteById(orderId);
        return true; //取消回滚成功
    }
}
